package us.styx.net;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

import us.styx.net.packet.PacketHandler;

public class NetworkEventHandler implements NetworkEvent {
    
    @Override
    public void readData(SelectionKey key) throws IOException {
	PacketHandler.processPackets(NetworkServer.acceptedConnections.get(key));
    }

    @Override
    public void writeData(SelectionKey key) {
	
    }
    
    @Override
    public void acceptConnection(SelectionKey key) {
	try {
	    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
	    SocketChannel socketChannel = serverSocketChannel.accept();
	    Socket socket = socketChannel.socket();
	    socketChannel.configureBlocking(false);
	    socketChannel.register(NetworkServer.selector, SelectionKey.OP_READ);
	    if (!NetworkServer.connections.contains(socket)) {
		NetworkServer.connections.add(socket);
	    } else {
		socket.close();
		return;
	    }
	    System.out.println("Incoming connection accepted from: [" + socket + "].");
	    if (NetworkServer.connections.contains(socket)) {
		key = socketChannel.register(NetworkServer.selector, SelectionKey.OP_READ);
		Client client = new Client(key);
		client.setChannel(socketChannel);
		client.setBuffer(ByteBuffer.allocateDirect(512));
		NetworkServer.connections.remove(socket);
		NetworkServer.acceptedConnections.put(key, client);
	    }
	} catch (IOException exception) {
	    exception.printStackTrace();
	}
    }
}